package spring.dao;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import spring.domain.User;
import spring.domain.UserLog;

import java.util.List;
import java.util.Objects;

public class UserDao  {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public User queryByNameAndPassword(String name, String password) {
        try{
            String sql="select * from user where name = ? and password = ?";
            return (User) this.jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class), name, password);
        }catch (Exception e){
            return null;
        }
    }

    public List<UserLog> queryAllLogs() {
        try{
            String sql="select * from login_info";
            return  this.jdbcTemplate.query(sql,new BeanPropertyRowMapper<UserLog>(UserLog.class));
        }catch (Exception e){
            return null;
        }
    }

    public void insertLog(UserLog userLog){
        String sql = "insert into login_info(ip,name,time) values(?,?,?)";
        Object[] args = {userLog.getIp(), userLog.getName(), userLog.getTime()};
        int update = jdbcTemplate.update(sql, args);
        if (update > 0){
            System.out.println("insert success");
        }else{
            System.out.println("insert fail");
        }
    }
}
